package com.gph.saviorframework.wf.controller;

import com.alibaba.fastjson.JSONObject;
import com.gph.saviorframework.Constants;
import com.gph.saviorframework.SaviorFrameworkException;
import com.gph.saviorframework.wf.service.ActivitiDefService;
import com.gph.saviorframework.wf.service.ActivitiInsService;
import com.gph.saviorframework.wf.service.ActivitiModelService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by root on 16-7-5.
 */
@Controller
@RequestMapping("/" + Constants.FRAMEWORK_REQUEST_PATH + "/wf")
public class WorkflowPlatformController {

    @Autowired
    private ActivitiDefService activitiDefService;

    @Autowired
    private ActivitiModelService activitiModelService;

    @Autowired
    private ActivitiInsService activitiInsService;

    private final String viewPrefix = Constants.FRAMEWORK_REQUEST_PATH+"/"+
            Constants.WORKFLOW_PLATFORM_PATH + "/";

    @RequestMapping(value = "/definition/list", method = RequestMethod.GET)
    public String definitionListPage() {
        return viewPrefix + "definition_list";
    }

    @RequestMapping(value = "/definition/list", method = RequestMethod.POST)
    @ResponseBody
    public String list(
            @RequestParam(value = Constants.DEFAULT_PAGE_MODEL_KEY, required = false, defaultValue = Constants.DEFAULT_PAGE_START) Integer start,
            @RequestParam(value = Constants.DEFAULT_RECORD_MODEL_KEY, required = false, defaultValue = Constants.DEFAULT_PAGE_SIZE) Integer limit,
            @RequestParam(value = Constants.DEFAULT_SORT_MODEL_KEY, required = false, defaultValue = Constants.DEFAULT_SORT_FIELD) String sort,
            @RequestParam(value = Constants.DEFAULT_DIR_MODEL_KEY, required = false, defaultValue = Constants.DEFAULT_SORT_DIRECTION) String dir,
            HttpServletRequest request) throws SaviorFrameworkException {
        String json = null;
        try {
            json = com.alibaba.fastjson.JSONArray.toJSONString(
                    activitiDefService.findAllProcessDefinitionMap((start - 1) * limit, limit,sort,dir));
        }
        catch (DataAccessException e) {
            e.printStackTrace();
        }
        return json;
    }

    @RequestMapping(value = "/definition/upload", method = RequestMethod.GET)
    public String definitionUploadPage() {
        return viewPrefix + "definition_upload";
    }

    /**
     * 上传流程定义文件
     * @param wfFile 流程定义文件
     */
    @RequestMapping(value = "/definition/upload", method = RequestMethod.POST)
    @ResponseBody
    public void uploadDefFile(@RequestParam(value = "wfFile")MultipartFile wfFile,
                              HttpServletResponse response) throws SaviorFrameworkException,IOException{
        JSONObject jsonObject = new JSONObject();
        try{
            activitiDefService.importProcessDefinition(wfFile.getOriginalFilename(), IOUtils.toByteArray(wfFile.getInputStream()));
            jsonObject.put(Constants.DEFAULT_SUCCESS_KEY,Boolean.TRUE);
            response.getWriter().print(jsonObject.toJSONString());
        }
        catch (Exception ex){
            ex.printStackTrace();
            jsonObject.put(Constants.DEFAULT_SUCCESS_KEY,Boolean.FALSE);
            response.getWriter().print(jsonObject.toJSONString());
        }
    }

    /**
     * 删除流程定义
     * @param deployIds 发布编号集合
     * @return
     * @throws SaviorFrameworkException
     */
    @RequestMapping(value = "/definition/delete", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap deleteDef(@RequestParam(value = "deployIds")String[] deployIds) throws SaviorFrameworkException{
        ModelMap modelMap = new ModelMap();
        try{
            for(String deployId : deployIds){
                activitiDefService.deleteProcessDefinition(deployId);
            }
            modelMap.put(Constants.DEFAULT_SUCCESS_KEY,Boolean.TRUE);
        }
        catch (Exception ex){
            ex.printStackTrace();
            modelMap.put(Constants.DEFAULT_SUCCESS_KEY,Boolean.FALSE);
        }

        return modelMap;
    }

    @RequestMapping(value = "/model/list", method = RequestMethod.GET)
    public String modelListPage() {
        return viewPrefix + "model_list";
    }

    /**
     * 获取模型列表
     * @param start
     * @param limit
     * @param dir
     * @param request
     * @return
     * @throws SaviorFrameworkException
     */
    @RequestMapping(value = "/model/list", method = RequestMethod.POST)
    @ResponseBody
    public String modelList(
            @RequestParam(value = Constants.DEFAULT_PAGE_MODEL_KEY, required = false, defaultValue = Constants.DEFAULT_PAGE_START) Integer start,
            @RequestParam(value = Constants.DEFAULT_RECORD_MODEL_KEY, required = false, defaultValue = Constants.DEFAULT_PAGE_SIZE) Integer limit,
            @RequestParam(value = Constants.DEFAULT_DIR_MODEL_KEY, required = false, defaultValue = Constants.DEFAULT_SORT_DIRECTION) String dir,
            HttpServletRequest request) throws SaviorFrameworkException {
        String json = null;
        try {
            json = com.alibaba.fastjson.JSONArray.toJSONString(
                    activitiModelService.findModelsMap((start - 1) * limit, limit,dir));
        }
        catch (DataAccessException e) {
            e.printStackTrace();
        }
        return json;
    }

    @RequestMapping(value = "/instance/list", method = RequestMethod.GET)
    public String instanceListPage() {
        return viewPrefix + "instance_list";
    }

    @RequestMapping(value = "/instance/list", method = RequestMethod.POST)
    @ResponseBody
    public String processInsList(
            @RequestParam(value = Constants.DEFAULT_PAGE_MODEL_KEY, required = false, defaultValue = Constants.DEFAULT_PAGE_START) Integer start,
            @RequestParam(value = Constants.DEFAULT_RECORD_MODEL_KEY, required = false, defaultValue = Constants.DEFAULT_PAGE_SIZE) Integer limit,
            @RequestParam(value = Constants.DEFAULT_SORT_MODEL_KEY, required = false, defaultValue = Constants.DEFAULT_SORT_FIELD) String sort,
            @RequestParam(value = Constants.DEFAULT_DIR_MODEL_KEY, required = false, defaultValue = Constants.DEFAULT_SORT_DIRECTION) String dir,
            HttpServletRequest request) throws SaviorFrameworkException {
        String json = null;
        try {
            json = com.alibaba.fastjson.JSONArray.toJSONString(
                    activitiInsService.findAllProcessInstanceMap((start - 1) * limit, limit,sort,dir));
        }
        catch (DataAccessException e) {
            e.printStackTrace();
        }
        return json;
    }

    @RequestMapping(value = "/instance/delete", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap deleteInstance(@RequestParam(value = "insIds")String[] insIds) throws SaviorFrameworkException{
        ModelMap modelMap = new ModelMap();
        try{
            for(String insId : insIds){
                activitiInsService.deleteRuningProcessInstance(insId);
            }
            modelMap.put(Constants.DEFAULT_SUCCESS_KEY,Boolean.TRUE);
        }
        catch (Exception ex){
            ex.printStackTrace();
            modelMap.put(Constants.DEFAULT_SUCCESS_KEY,Boolean.FALSE);
        }

        return modelMap;
    }
}
